//
//  YMHealthFileViewDateView.m
//  YMMedical
//
//  Created by y s on 2023/7/20.
//

#import "YMHealthFileViewDateView.h"
#import <FSCalendar/FSCalendar.h>
#import "YMHomeChooseYearSheet.h"
#import "NSDate+Category.h"
#import "YMHomeService.h"

@interface YMHealthFileViewDateView ()<FSCalendarDelegate, FSCalendarDataSource>

@property (nonatomic, strong) UIView *vBg;

@property (nonatomic, strong) UIImageView *imgvIcon;
@property (nonatomic, strong) UILabel *lblDate;
@property (nonatomic, strong) UIImageView *imgvArrow;
@property (nonatomic, strong) UIButton *btnDate;

@property (nonatomic, strong) FSCalendar *calendar;

@property (nonatomic, strong) NSDateFormatter *dateFormatter;

@property (nonatomic, copy) NSString *startDate;
@property (nonatomic, copy) NSString *endDate;

@property (nonatomic, strong) NSMutableArray *arrEvents;

@property (nonatomic, strong) NSMutableArray *arrData;

@property (nonatomic, assign) BOOL isFirst;

@end

@implementation YMHealthFileViewDateView

- (instancetype)init{
    self = [super init];
    if (self) {
        _isFirst = YES;
        [self setUI];
    }
    return self;
}

#pragma mark -- UI
- (void)setUI{
    
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, [SFitUtil fit:395]);
    
    [self addSubview:self.vBg];
    [self.vBg addSubview:self.calendar];
    [self.vBg addSubview:self.btnDate];
    [self.btnDate addSubview:self.imgvIcon];
    [self.btnDate addSubview:self.lblDate];
    [self.btnDate addSubview:self.imgvArrow];
    
    [self.vBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo([SFitUtil fit:15]);
        make.top.mas_equalTo([SFitUtil fit:15]);
        make.right.mas_equalTo([SFitUtil fit:-15]);
        make.bottom.mas_equalTo([SFitUtil fit:-16]);
    }];
    [self.btnDate mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo([SFitUtil fit:30+22]);
    }];
    [self.imgvIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo([SFitUtil fit:15]);
        make.size.mas_equalTo([SFitUtil fitSize:22 height:22]);
        make.centerY.mas_equalTo(0);
    }];
    [self.lblDate mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imgvIcon.mas_right).offset([SFitUtil fit:5]);
        make.centerY.mas_equalTo(0);
    }];
    [self.imgvArrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.lblDate.mas_right).offset([SFitUtil fit:5]);
        make.centerY.mas_equalTo(0);
        make.size.mas_equalTo([SFitUtil fitSize:22 height:22]);
        make.right.mas_equalTo([SFitUtil fit:-15]);
    }];
    [self changeStartAndEndData:[NSDate date]];
}

- (void)loadData{
    WEAK_SELF;
    if (self.detectionUserId == nil || self.detectionUserId.length < 1 ||
        self.minorTermId == nil || self.minorTermId.length < 1 ||
        self.startDate == nil || self.startDate.length < 1){
        return;
    }
    [YMHomeService requestHomeGetHealthCalendarRecordDetails:self.detectionUserId minorTermId:self.minorTermId collectStartDate:self.startDate collectEndDate:self.endDate success:^(NSArray * _Nonnull arrItem) {
        [weakSelf.arrEvents removeAllObjects];
        [weakSelf.arrData removeAllObjects];
        [weakSelf.arrData addObjectsFromArray:arrItem];
        for (NSDictionary *item in arrItem) {
            NSArray *arrTemp = [SDataUtil arrayOf:item[@"DetectionDetails"]];
            if (arrTemp.count > 0){
                NSString *dateStr = [SDataUtil stringOf:item[@"collectDate"] valid:@""];
                if (dateStr != nil && dateStr.length > 0){
                    [weakSelf.arrEvents addObject:dateStr];
                }
            }
        }
        if (weakSelf.isFirst){
            [weakSelf.calendar selectDate:[NSDate date]];
            [weakSelf selectCalendarWithDate:[NSDate date]];
            weakSelf.isFirst = NO;
        }else{
            [weakSelf selectCalendarWithDate:weakSelf.calendar.selectedDate];
        }
        [weakSelf.calendar reloadData];
    } failure:^(NSString * _Nonnull message) {
        [SHUD showInfo:message];
    }];
}
- (void)updateData:(NSString *)dateStr
         arrRecord:(NSArray *)arrRecord{
    if ([self.arrEvents containsObject:dateStr]){
        if (arrRecord.count < 1){
            [self.arrEvents removeObject:dateStr];
            [self.calendar reloadData];
        }
        for (int i = 0; i < self.arrData.count; i++) {
            NSDictionary *item = [SDataUtil dictOf:self.arrData[i]];
            NSString *collectDate = [SDataUtil stringOf:item[@"collectDate"] valid:@""];
            if (collectDate != nil && collectDate.length > 0 &&
                [dateStr isEqualToString:collectDate]){
                NSMutableDictionary *dictTemp = [[NSMutableDictionary alloc] initWithDictionary:item];
                [dictTemp setValue:arrRecord forKey:@"DetectionDetails"];
                [self.arrData replaceObjectAtIndex:i withObject:[dictTemp copy]];
                break;
            }
        }
    }
}

- (void)dateClickAction:(id)sender{
    YMHomeChooseYearSheet *sheet = [[YMHomeChooseYearSheet alloc] init];
    sheet.dateFormat = [NSString stringWithFormat:@"yyyy%@MM%@",KLanguage(@"year_txt"),KLanguage(@"month_txt")];
    WEAK_SELF;
    sheet.sureDateBlock = ^(NSString * _Nonnull dateStr) {
        NSString *dateNow = [NSString stringWithFormat:@"%@01%@",dateStr,KLanguage(@"day_txt")];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = [NSString stringWithFormat:@"yyyy%@MM%@dd%@",KLanguage(@"year_txt"),KLanguage(@"month_txt"),KLanguage(@"day_txt")];
        NSDate *date = [formatter dateFromString:dateNow];
        if ([weakSelf isSameYearMonth:date] == false){
            [weakSelf.calendar setCurrentPage:date animated:YES];
            [weakSelf changeStartAndEndData:date];
        }
        weakSelf.lblDate.text = dateStr;
//        [weakSelf.calendar reloadData];
    };
    [sheet show];
}

- (NSString *)getMonthFirstDayWithDate:(NSDate *)date{
    NSDate *newDate = date;
    double interval = 0;
    NSDate * firstDate = nil;
    NSCalendar * calendar = [NSCalendar currentCalendar];
    BOOL bl = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&firstDate interval:&interval forDate:newDate];
    if(bl) {
        NSString *firstString = [self.dateFormatter stringFromDate:firstDate];
        return firstString;
    }
    return @"";
}
//获取某月的最后一天字符串
- (NSString *)getMonthLastDayWithDate:(NSDate *)date {
    NSDate *newDate = date;
    double interval = 0;
    NSDate *firstDate = nil;
    NSDate *lastDate = nil;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    BOOL bl = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&firstDate interval:&interval forDate:newDate];
    if(bl) {
        lastDate = [firstDate dateByAddingTimeInterval:interval -1];
        NSString *lastString = [self.dateFormatter stringFromDate:lastDate];
        return lastString;
    }
    return @"";
}

- (void)changeStartAndEndData:(NSDate *)date{
    if (date == nil){
        return;
    }
    self.startDate = [self getMonthFirstDayWithDate:date];
    self.endDate = [self getMonthLastDayWithDate:date];
    [self loadData];
}

#pragma mark -- FSCalendarDataSource
- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar {
    return [NSDate date];
}

//- (NSArray *)eventsForDate:(NSDate *)date{
//
//    NSArray *filteredEvents = [self.events filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(EKEvent * _Nullable evaluatedObject, NSDictionary* _Nullable bindings) {
//
//return [evaluatedObject.occurrenceDate isEqualToDate:date];
//
//}]];

- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date{
    //要标记的日期显示圆点1个其他不显示
    NSString *dateStr = [self.dateFormatter stringFromDate:date];
    if ([self.arrEvents containsObject:dateStr]) {
        return 1;
    }else{
        //特殊日期标记
        return 0;
    }
}

#pragma mark -- FSCalendarDelegate
- (BOOL)calendar:(FSCalendar *)calendar shouldSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    
    return [self isSameYearMonth:date];
}
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    [self selectCalendarWithDate:date];
}
- (void)selectCalendarWithDate:(NSDate *)date{
    NSString *dateStr = [self.dateFormatter stringFromDate:date];
    NSArray *arrTemp = @[];
    if ([self.arrEvents containsObject:dateStr]){
        for (NSDictionary *item in self.arrData) {
            NSString *collectDate = [SDataUtil stringOf:item[@"collectDate"] valid:@""];
            if (collectDate != nil && collectDate.length > 0 &&
                [dateStr isEqualToString:collectDate]){
                arrTemp = [SDataUtil arrayOf:item[@"DetectionDetails"]];
                break;
            }
        }
    }
    if (self.chooseDateBlock){
        self.chooseDateBlock(dateStr,arrTemp);
    }
}

- (BOOL)isSameYearMonth:(NSDate *)date{
    NSString *dateNow = [NSString stringWithFormat:@"%@01%@",self.lblDate.text,KLanguage(@"day_txt")];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = [NSString stringWithFormat:@"yyyy%@MM%@dd%@",KLanguage(@"year_txt"),KLanguage(@"month_txt"),KLanguage(@"day_txt")];
    NSDate *dateN = [dateFormatter dateFromString:dateNow];
    NSInteger thisMonth = [dateN getDateComponents].month;
    NSInteger calendarMonth = [date getDateComponents].month;
    NSInteger thisYear = [dateN getDateComponents].year;
    NSInteger calendarYear = [date getDateComponents].year;
    if (thisMonth == calendarMonth && thisYear == calendarYear){
        return YES;
    }
    return NO;
}


#pragma mark -- setter and getter
- (UIView *)vBg{
    if (_vBg == nil){
        _vBg = [[UIView alloc] init];
        _vBg.backgroundColor = STheme.D9;
        _vBg.clipsToBounds = YES;
        _vBg.layer.cornerRadius = [SFitUtil fit:8];
    }
    return _vBg;
}
- (UIImageView *)imgvIcon{
    if (_imgvIcon == nil){
        _imgvIcon = [[UIImageView alloc] init];
        _imgvIcon.image = [UIImage imageNamed:@"home_health_file_calender_icon"];
    }
    return _imgvIcon;
}
- (UILabel *)lblDate{
    if (_lblDate == nil){
        _lblDate = [[UILabel alloc] init];
        _lblDate.textColor = STheme.D0;
        _lblDate.font = [SFitUtil fitBoldFont:15];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = [NSString stringWithFormat:@"yyyy%@MM%@",KLanguage(@"year_txt"),KLanguage(@"month_txt")];
        NSString *dateStr = [formatter stringFromDate:[NSDate date]];
        _lblDate.text = dateStr;
    }
    return _lblDate;
}
- (UIImageView *)imgvArrow{
    if (_imgvArrow == nil){
        _imgvArrow = [[UIImageView alloc] init];
        _imgvArrow.image = [UIImage imageNamed:@"home_nav_updown_arrow"];
    }
    return _imgvArrow;
}
- (UIButton *)btnDate{
    if (_btnDate == nil){
        _btnDate = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnDate addTarget:self action:@selector(dateClickAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnDate;
}
- (FSCalendar *)calendar{
    if (_calendar == nil){
        _calendar = [[FSCalendar alloc] initWithFrame:CGRectMake( 0, [SFitUtil fit:20], SCREEN_WIDTH-[SFitUtil fit:30], [SFitUtil fit:330])];
        _calendar.backgroundColor = [UIColor clearColor];
        _calendar.delegate = self;
        _calendar.dataSource = self;
        _calendar.appearance.weekdayTextColor = STheme.D1;
        _calendar.appearance.weekdayFont = [SFitUtil fitFont:12];
        _calendar.appearance.headerTitleColor = [UIColor clearColor];
        _calendar.appearance.titleDefaultColor = STheme.D1;
        _calendar.appearance.titleFont = [SFitUtil fitFont:12];
        _calendar.appearance.titlePlaceholderColor = [SUIUtil colorOf:0xAAAAAA];
        _calendar.appearance.titleSelectionColor = STheme.D12;
        _calendar.appearance.selectionColor = [SUIUtil colorOf:STheme.H_D12 alpha:0.2];
        _calendar.appearance.todayColor = [UIColor clearColor];
        _calendar.appearance.titleTodayColor = STheme.D1;
        _calendar.appearance.eventDefaultColor = STheme.D12;
        _calendar.appearance.eventSelectionColor = STheme.D12;
//        [_calendar selectDate:[NSDate date]];
        _calendar.scope = FSCalendarScopeMonth;
        _calendar.scrollEnabled = NO;
    }
    return _calendar;
}
- (NSDateFormatter *)dateFormatter{
    if (_dateFormatter == nil){
        _dateFormatter = [[NSDateFormatter alloc] init];
        _dateFormatter.dateFormat = @"yyyy-MM-dd";
    }
    return _dateFormatter;
}
- (NSMutableArray *)arrEvents{
    if (_arrEvents == nil){
        _arrEvents = [[NSMutableArray alloc] init];
    }
    return _arrEvents;
}
- (NSMutableArray *)arrData{
    if (_arrData == nil){
        _arrData = [[NSMutableArray alloc] init];
    }
    return _arrData;
}

@end
